package greet

import (
	"github.com/gin-gonic/gin"

	"github.com/zeromicro/go-zero/tools/goctl/example/api/internal/domain"
	"github.com/zeromicro/go-zero/tools/goctl/example/api/internal/logic"
	"github.com/zeromicro/go-zero/tools/goctl/example/api/internal/svc"
	"github.com/zeromicro/go-zero/tools/goctl/example/api/pkg/httpx"
)

type Admin struct {
	svcCtx *svc.ServiceContext
	admin  logic.Admin
	role   logic.Role
}

func NewAdmin(svcCtx *svc.ServiceContext, admin logic.Admin, role logic.Role) *Admin {
	return &Admin{
		svcCtx: svcCtx,
		admin:  admin,
		role:   role,
	}
}

func (h *Admin) InitRegister(engine *gin.Engine) {
	glogin := engine.Group("v1/admin")
	glogin.POST("/login", h.Login)
	glogin.POST("/create", h.Create)
	glogin.GET("/find/:id", h.Find)
	glogin.GET("/list", h.List)

	g1 := engine.Group("v1/role/admin", h.svcCtx.Jwt.Handler)
	g1.POST("/SetAdmin", h.SetAdmin)
}

// 后台登入
func (h *Admin) Login(ctx *gin.Context) {
	var req domain.LoginReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.admin.Login(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

// 创建
func (h *Admin) Create(ctx *gin.Context) {
	var req domain.AdminModel
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	err := h.admin.Create(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.Ok(ctx)
	}
}

// 查找
func (h *Admin) Find(ctx *gin.Context) {
	res, err := h.admin.Find(ctx.Request.Context())
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

// 查找
func (h *Admin) List(ctx *gin.Context) {
	var req domain.AdminListReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.admin.List(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}

// 管理员详情
func (h *Admin) SetAdmin(ctx *gin.Context) {
	var req domain.SetAdminRoleReq
	if err := httpx.BindAndValidate(ctx, &req); err != nil {
		httpx.FailWithErr(ctx, err)
		return
	}

	res, err := h.role.SetAdmin(ctx.Request.Context(), &req)
	if err != nil {
		httpx.FailWithErr(ctx, err)
	} else {
		httpx.OkWithData(ctx, res)
	}
}
